import {createRouter, createWebHistory} from 'vue-router'

import NProgress from 'nprogress'
import tool from '@/utils/tool';
import config from "@/config"


let menus = [];
const modules = import.meta.glob("./modules/**", {eager: true});
for (const modulesKey in modules) {
    const mod = modules[modulesKey].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    menus.push(...modList);
}


const commonModules = import.meta.glob("./common/**", {eager: true});
for (const modulesKey in commonModules) {
    const mod = commonModules[modulesKey].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    menus.push(...modList);
}

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            name: "layout",
            path: "/",
            component: () => import( "./../layout/index.vue"),
            redirect: '/login',
            children: [
                {
                    name: "home",
                    path: "/home",
                    component: () => import("./../views/HomeView.vue"),
                    meta: {
                        title: "首页",
                        icon: "el-icon-platform-eleme"
                    },
                },
                ...menus,
            ]
        },
        {
            path: '/about',
            name: 'about',
            // route level code-splitting
            // this generates a separate chunk (About.[hash].js) for this route
            // which is lazy-loaded when the route is visited.
            component: () => import('../views/AboutView.vue')
        },
        {
            path: '/login',
            name: 'login',
            // route level code-splitting
            // this generates a separate chunk (About.[hash].js) for this route
            // which is lazy-loaded when the route is visited.
            component: () => import('../views/LoginView.vue')
        },

    ]
})


router.beforeEach((to, from, next) => {
    NProgress.start()
    //动态标题
    document.title = to.meta.title ? `${to.meta.title} - ${config.APP_NAME}` : `${config.APP_NAME}`
    let sessionId = tool.data.get("sessionId");
    if (to.path === "/login") {
        next();
        return false;
    }
    if (!sessionId) {
        next({
            path: '/login'
        });
        return false;
    }
    next();
});

router.afterEach(() => {
    NProgress.done()
});


export default router
